<script setup>
import router from '@/router';
import { useAuthStore } from '@/stores/auth';
import { ElMessageBox, ElMessage } from 'element-plus';
import { ref, getCurrentInstance } from 'vue';
import { useTokenStore } from '@/stores/token.js';
import { useInfoStore } from '@/stores/info.js';
import { deleteAccountService } from '@/api/user.js';
import {getUserIsBuyService, getUserIsMemberService} from "@/api/type.js"; // 导入注销接口

const { $t } = getCurrentInstance().proxy;
const auth = useAuthStore();
const tokenStore = useTokenStore();
const userInfoStore = useInfoStore();
const hasStaff = ref(false);
const displayByVip = async () => {
  hasStaff.value = false;
  let res = await getUserIsMemberService();
  if(res.data.memberType !== 'normal'){
    hasStaff.value = true;
  }else{
    res = await getUserIsBuyService();
    if(res.data.package8Owned === true){
      hasStaff.value = true;
    }
  }
};
displayByVip();

// 普通登出（保持原有功能）
const handleReload = () => {
  userInfoStore.setInfo('');
  tokenStore.token = '';
  router.push('/sign');
  auth.setLogin(false);
};

// 注销账号（新增功能）
const handleDeleteAccount = async () => {
  try {
    // 第一步：弹出密码输入框
    const password = await new Promise((resolve, reject) => {
      ElMessageBox.prompt($t('cancelAccountConfirmContent'), $t('cancelAccountTitle'), {
        confirmButtonText: $t('confirm'),
        cancelButtonText: $t('cancel'),
        inputType: 'password',
        inputPlaceholder: $t('enterPasswordPlaceholder'),
        inputValidator: (value) => {
          if (!value) return $t('passwordRequired');
          return true;
        },
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            if (!instance.inputValue) {
              instance.inputErrorMessage = $t('passwordRequired');
              done(false);
            } else {
              done();
            }
          } else {
            done();
          }
        }
      })
          .then(({ value }) => resolve(value))
          .catch(() => reject('canceled'));
    });

    // 第二步：显示最终确认警告
    await ElMessageBox.confirm(
        $t('permanentDeleteWarning'),
        $t('finalConfirmation'),
        {
          confirmButtonText: $t('confirmDelete'),
          cancelButtonText: $t('cancel'),
          type: 'error',
          confirmButtonClass: 'el-button--danger',
          dangerouslyUseHTMLString: true
        }
    );

    // 第三步：调用注销接口
    const response = await deleteAccountService({ password });

    // 根据request.js的拦截器处理，状态码0表示成功
    if (response.code === 0) {
      // 清除用户数据
      userInfoStore.setInfo('');
      tokenStore.token = '';

      // 跳转到登录页
      await router.push('/sign');
      // 显示成功通知
      ElMessage({
        type: 'success',
        message: $t('accountDeletedSuccess'),
        duration: 3000
      });
    } else {
      // 处理业务错误
      throw new Error(response.msg || $t('deleteFailed'));
    }
  } catch (error) {
    if (error !== 'canceled') {
      // 显示错误通知
      ElMessage({
        type: 'error',
        message: error.message || $t('deleteError'),
        duration: 3000
      });
    }
  }
};
</script>

<template>
  <div class="settings-content">
    <div class="content-header">
      <h2>{{ $t("setting4") }}</h2>
      <p>{{ $t("accountManagementDesc") }}</p>
    </div>
    <div class="settings-card">
      <h3><i class="fa-solid fa-arrow-right-from-bracket"></i> {{ $t("logoutAndCancel") }}</h3>
      <div class="setting-item">
        <div class="setting-info">
          <h4>{{ $t("logoutTitle") }}</h4>
          <p>{{ $t("logoutDesc") }}</p>
        </div>
        <button class="action-btn logout-btn" @click="handleReload">{{ $t("logoutTitle") }}</button>
      </div>
      <div class="setting-item">
        <div class="setting-info">
          <h4>{{ $t("cancelAccountTitle") }}</h4>
          <p>{{ $t("cancelAccountDesc") }}</p>
        </div>
        <button class="action-btn cancel-btn" @click="handleDeleteAccount">
          {{ $t("cancelAccountTitle") }}
        </button>
      </div>
    </div>
    <div class="settings-card" v-if="hasStaff">
      <h3><i class="fa-solid fa-headphones"></i> {{ $t("exclusiveCustomerService") }} </h3>
      <div class="setting-item">
        <div class="setting-info">
          <h4>{{ $t("contactServiceTitle") }}</h4>
          <p>{{ $t("contactServiceDesc") }}</p>
        </div>
        <button class="action-btn call-btn" >
          <a href="mailto:2056941306＠qq.com">{{ $t("contactServiceTitle") }}</a>
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.settings-content {
  background: var(--bgcolor);
  border-radius: 16px;
  box-shadow: 0 6px 25px rgba(0, 0, 0, 0.07);
  padding: 40px;
  min-height: 500px;
  max-width: 1000px;
  margin-left: calc(50vw - 500px);
  color: var(--txcolor);
  border: 1px solid var(--border-color);
}

.content-header {
  margin-bottom: 30px;
}

.content-header h2 {
  font-size: 1.8rem;
  color: var(--header-color);
  margin-bottom: 10px;
}

.content-header p {
  color: var(--secondary-text);
  font-size: 1rem;
  max-width: 600px;
  line-height: 1.6;
}

.settings-card {
  background: var(--card-bg);
  border-radius: 12px;
  padding: 25px;
  margin-bottom: 25px;
  border: 1px solid var(--border-color);
}

.settings-card h3 {
  font-size: 1.2rem;
  color: var(--header-color);
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.settings-card h3 i {
  color: var(--accent-color);
}

.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f1f5f9;
}

.setting-item:last-child {
  border-bottom: none;
}

.setting-info h4 {
  font-size: 1rem;
  color: var(--h4-color);
  margin-bottom: 5px;
}

.setting-info p {
  font-size: 0.9rem;
  color: #64748b;
  max-width: 500px;
}

.action-btn {
  padding: 8px 10px;
  border-radius: 10px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  border: none;
  display: flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.08);
  min-width: 140px;
  justify-content: center;
}

.logout-btn {
  background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
  color: white;
}

.logout-btn:hover {
  background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(37, 99, 235, 0.25);
}

.logout-btn:active {
  transform: translateY(1px);
  box-shadow: 0 2px 4px rgba(37, 99, 235, 0.3);
}

.cancel-btn {
  background: linear-gradient(135deg, #f87171 0%, #ef4444 100%);
  color: white;
}

.cancel-btn:hover {
  background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(239, 68, 68, 0.25);
}

.cancel-btn:active {
  transform: translateY(1px);
  box-shadow: 0 2px 4px rgba(239, 68, 68, 0.3);
}

.call-btn {
  background: linear-gradient(135deg, #34d399 0%, #10b981 100%);
  color: white;
}

.call-btn:hover {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(16, 185, 129, 0.25);
}
</style>